//
// Created by delin10 on 2020/5/15.
//
#include <sys/types.h>
#include <unistd.h>
#include <stdio.h>
#include <errno.h>
#include <string.h>

int main() {
    pid_t ret;
    int pipe_fds[2];
    pipe(pipe_fds);
    // 子进程执行逻辑
    if ((ret = fork()) == 0) {
        char buff[] = "来自子进程的消息";
        int w;
        if ((w = write(pipe_fds[1], buff, strlen(buff))) <  0) {
            printf("%s", strerror(errno));
        }// 父进程执行逻辑
    } else if (ret > 0) {
        char buff[1024];
        printf("创建子进程成功！PID = %d\n", ret);
        int read_code;
        if ((read_code = read(pipe_fds[0], buff, 1024)) > 0) {
            buff[read_code] = '\0';
            printf("收到子进程消息：%s\n", buff);
        } else if (read_code == 0){
            printf("无消息");
        } else {
            printf("%s", strerror(errno));
        }
    } else {
        printf("创建子进程失败！errno = %d, 错误消息为：%s", errno, strerror(errno));
    }
    // 关闭管道
    // 父进程和子进程都会调用一次，使得文件描述符的引用次数减少至0
    close(pipe_fds[0]);
    close(pipe_fds[1]);
}